package com.tuozixuan.handler;

import static com.tuozixuan.constant.GitConstants.PASSWORD;
import static com.tuozixuan.constant.GitConstants.USERNAME;

import java.io.File;
import java.util.Map;

import org.eclipse.jgit.api.CreateBranchCommand;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.transport.CredentialsProvider;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.tuozixuan.config.Config;
import com.tuozixuan.util.GitUtils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.setting.yaml.YamlUtil;

public class CloneProjectHandler {

	private static Logger logger = LoggerFactory.getLogger(CloneProjectHandler.class);

	public static void main(String[] args) throws Exception {
		
		CredentialsProvider credentialsProvider = new UsernamePasswordCredentialsProvider(USERNAME, PASSWORD);
		Config config = YamlUtil.loadByPath("config.yml", Config.class);
		Map<String, String> projectMap = config.getProjects();
		for (Map.Entry<String, String> entry : projectMap.entrySet()) {	
			String projectName = entry.getKey();
			String branchName = entry.getValue();
			
			String projectPath = config.getBasePath() + File.separator + projectName;
			logger.info("[{}]projectPath:{}", projectName, projectPath);
			if (FileUtil.exist(projectPath)) {
				logger.warn("[{}]{}已经存在，跳过clone操作", projectName, projectPath);
				continue;
			}
			
			File projectWorkPath = new File(projectPath);
			String gitUrl = String.format("http://gitlab.zerofinance.net/hk-cash/%s.git", projectName);
			Git git = Git.cloneRepository().setURI(gitUrl).setDirectory(projectWorkPath)
			        .setCredentialsProvider(credentialsProvider).call();
			boolean existRemoteBranch = GitUtils.existRemoteBranch(git, branchName);
			if (existRemoteBranch) {
				git.checkout().setCreateBranch(true).setName(branchName)
	            	.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK)
	            	.setStartPoint("origin/" + branchName).call();
				git.close();
			} else {
				logger.error("[{}]{}远程分支不存在，跳过clone操作", projectPath, branchName);
				continue;
			}
		}
		
	}
}
